<?php
	$required = false;
	$title = stripslashes($_POST['title']);
	
	if ( function_exists('sanitize_url') ) {
		$url = sanitize_url(strip_tags(stripslashes(($_POST['url']))));
	} else {
		$url = clean_url(strip_tags(stripslashes(($_POST['url']))));
	}
	
	switch ( $_GET['page'] ) :
		case 'quote':
			$page = 'quote';
			
			$form = '
			<div class="stuffbox">
				<h3><label for="title">Title</label></h3>
				<div class="inside">
					<input type="text" name="title" id="title" value="" size="30" style="width: 95%" />
				</div>
			</div>
			
			<div class="stuffbox">
				<h3><label for="quote">Quote</label> (required)</h3>
				<div class="inside">
					<textarea name="quote" id="quote" class="quote" cols="50" rows="10" style="width: 95%"></textarea>
				</div>
			</div>
			
			<div class="stuffbox">
				<h3><label>Source</label> (optional)</h3>
				<div class="inside">
					<table class="form-table" style="width: 100%;" cellspacing="2" cellpadding="5">
					<tr class="form-field">
						<th valign="top" scope="row"><label for="name">Name</label></th>
						<td><input type="text" name="name" id="name" size="50" value="" style="width: 95%" /></td>
					</tr>
					<tr class="form-field">
						<th valign="top" scope="row"><label for="url">URL</label></th>
						<td><input type="text" name="url" id="url" size="50" value="" style="width: 95%" /></td>
					</tr>
					<tr class="form-field">
						<th valign="top" scope="row"><label for="custom">Custom</label></th>
						<td><script type="text/javascript">edToolbar()</script><textarea name="custom" id="custom" cols="50" rows="10" style="width: 95%"></textarea><script type="text/javascript">var edCanvas = document.getElementById("custom");</script></td>
					</tr>					
					</table>
					<p>This can either be:</p>
					<ul><li>Name and URL</li><li>Name</li><li>URL</li><li>Custom</li></ul>					
				</div>
			</div>
			';

			if ( isset($_POST['publish']) ) {
				$quote = stripslashes($_POST['quote']);
				$name = stripslashes($_POST['name']);
				$custom = stripslashes($_POST['custom']);
				
				$content = '<blockquote>';
				$content .= "\n" . $quote . "\n";
	
				if ( !empty($name) || !empty($url) || !empty($custom) ) {				
					switch ( true ):
						case ($name && $url):
							$source = '<cite><a href="'.$url.'">'.$name.'</a></cite>';
							break;
						case ($name):
							$source = $name; 
							break;
						case ($url):
							$source = '<cite><a href="'.$url.'">'.$url.'</a></cite>';
							break;
						case ($custom):
							$source = $custom;
							break;
					endswitch;
						
					$content .= "\n" . '&mdash; ' . $source . "\n";
				}
				
				$content .= '</blockquote>';
			
				if ( !empty($quote) )
					$required = true;
			}
			break;
		
		case 'video':
			$page = 'video';
			
			$form = '
			<div class="stuffbox">
				<h3><label for="title">Title</label></h3>
				<div class="inside">
					<input type="text" name="title" id="title" value="" size="30" style="width: 95%" />
				</div>
			</div>
			
			<div class="stuffbox">
				<h3><label>Video URL or Embed-tag</label> (required)</h3>
				<div class="inside">
					<table class="form-table" style="width: 100%;" cellspacing="2" cellpadding="5">
					<tr class="form-field">
						<th valign="top" scope="row"><label for="url">URL</label></th>
						<td><input type="text" name="url" id="url" size="50" value="" style="width: 95%" /></td>
					</tr>
					<tr class="form-field">
						<th valign="top" scope="row"><label for="embedtag">Embed-tag</label></th>
						<td><textarea name="embedtag" id="embedtag" cols="50" rows="10" style="width: 95%"></textarea></td>
					</tr>
					</table>
					<p>This can be a URL from video sites like YouTube or Google Video, or the raw Embed-tag from any video/flash site. (ie. http://youtube.com/watch?v=1kdRYdQ5lZo)</p>					
				</div>
			</div>

			<div class="stuffbox">
				<div class="inside">
					<table class="form-table" style="width: 100%;" cellspacing="2" cellpadding="5">
					<tr class="form-field">
						<th valign="top" scope="row"><label for="caption">Caption</label></th>
						<td><input type="text" name="caption" id="caption" size="50" value="" style="width: 95%" /></td>
					</tr>
					<tr class="form-field">
						<th valign="top" scope="row"><label for="description">Description</label></th>
						<td><script type="text/javascript">edToolbar()</script><textarea name="description" id="description" cols="50" rows="10" style="width: 95%"></textarea><script type="text/javascript">var edCanvas = document.getElementById("description");</script></td>
					</tr>
					</table>
				</div>	
			</div>		
			';

			if ( isset($_POST['publish']) ) {
				$embedtag = stripslashes($_POST['embedtag']);
				$description = stripslashes($_POST['description']);	
				$caption = stripslashes($_POST['caption']);
				
				if ( !empty($url) ) {
					switch ( true ):
						case preg_match('#youtube.com/watch#i', $url):
							$url = preg_replace('#youtube.com/watch\?v=#i', 'youtube.com/v/', $url);
							$content = '<object width="425" height="350"><param name="movie" value="'.$url.'&amp;fs=1&amp;rel=0&amp;border=1&amp;color1=0xeeeeee&amp;color2=0xeeeeee"></param><param name="allowFullScreen" value="true"><embed src="'.$url.'&amp;fs=1&amp;rel=0&amp;border=1&amp;color1=0xeeeeee&amp;color2=0xeeeeee" type="application/x-shockwave-flash" allowfullscreen="true" width="425" height="350"></embed></object>';
							break;
							
						case preg_match('#video.google.com/videoplay#i', $url):
							$url = preg_replace('#video.google.com/videoplay\?docid=#i', 'video.google.com/googleplayer.swf?docId=', $url );					
							$content = '<embed style="width:400px; height:326px" id="VideoPlayback" type="application/x-shockwave-flash" src="'.$url.'" flashvars=""> </embed>';	
							break;
							
						case preg_match('#vimeo.com/#i', $url);
							$url = preg_replace('#vimeo.com/#i', 'vimeo.com/moogaloop.swf?clip_id=', $url);
							$content = '<object type="application/x-shockwave-flash" width="480" height="360" data="'.$url.'&amp;server=vimeo.com&amp;fullscreen=1&amp;show_title=1&amp;show_byline=1&amp;show_portrait=1&amp;color=00ADEF">	<param name="quality" value="best" />	<param name="allowfullscreen" value="true" />	<param name="scale" value="showAll" />	<param name="movie" value="'.$url.'&amp;server=vimeo.com&amp;fullscreen=1&amp;show_title=1&amp;show_byline=1&amp;show_portrait=1&amp;color=00ADEF" /></object>';
							break;
							
						case preg_match('#revver.com/video/#i', $url);
							if (substr($url, -1, 1) == '/')
								$url = substr_replace($url, '', -1, 1);
														
							$url = preg_replace('#http://(www.revver|revver)\.com/video/(.*?)/(.+)#i', '\2', $url);
							$content = '<object width="480" height="392" data="http://flash.revver.com/player/1.0/player.swf?mediaId='.$url.'" type="application/x-shockwave-flash"><param name="Movie" value="http://flash.revver.com/player/1.0/player.swf?mediaId='.$url.'"></param><param name="FlashVars" value="allowFullScreen=true"></param><param name="AllowFullScreen" value="true"></param><param name="AllowScriptAccess" value="always"></param><embed type="application/x-shockwave-flash" src="http://flash.revver.com/player/1.0/player.swf?mediaId='.$url.'" pluginspage="http://www.macromedia.com/go/getflashplayer" allowScriptAccess="always" flashvars="allowFullScreen=true" allowfullscreen="true" height="392" width="480"></embed></object>';
							break;							
							
						case preg_match('#metacafe.com/watch/#i', $url);					
							if (substr($url, -1, 1) == '/')
								$url = substr_replace($url, '', -1, 1);
							
							$url = preg_replace('#watch/(.+)#i', 'fplayer/\1\2.swf', $url);							
							$content = '<embed src="'.$url.'" width="400" height="345" wmode="transparent" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"> </embed>';
							break;
						
						case preg_match('#viddler.com/#i', $url);
							$viddler = wp_remote_fopen($url);
						
							if (preg_match("/<link\s+rel=\"video_src\"\s+href=\"http:\/\/(www\.)?viddler.com\/player\/([0-9a-fA-F]+)/", $viddler, $matches)) {
								$content = '<object type="application/x-shockwave-flash" data="http://www.viddler.com/simple/'.$matches[2].'/" width="500" height="301" id="viddler_'.$matches[2].'"><param name="movie" value="http://www.viddler.com/simple/'.$matches[2].'/" /><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="true" /></object>';
							}						
							break;
							
						case preg_match('#flickr.com/photos/#i', $url);
							$url = preg_replace('#http://(www.flickr|flickr)\.com/photos/(.+)/(\d+)(.*?)#i', '\3', $url);
							$content = '<object type="application/x-shockwave-flash" width="400" height="300" data="http://www.flickr.com/apps/video/stewart.swf?v=60247" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"> <param name="flashvars" value="intl_lang=en-us&amp;photo_id='.$url.'"></param> <param name="movie" value="http://www.flickr.com/apps/video/stewart.swf?v=60247"></param> <param name="bgcolor" value="#000000"></param> <param name="allowFullScreen" value="true"></param><embed type="application/x-shockwave-flash" src="http://www.flickr.com/apps/video/stewart.swf?v=60247" bgcolor="#000000" allowfullscreen="true" flashvars="intl_lang=en-us&amp;photo_id='.$url.'" height="300" width="400"></embed></object>';
							
							break;	
							
						default:
							$content = $url;
							break;
					endswitch;
				} else {
					$content = $embedtag;
				}
							
				if ( !empty($description) )
					$content .= "\n\n" . $description;
				
				if ( !empty($url) || !empty($embedtag) )
					$required = true;
			}
			break;
		
		case 'link':
			$page = 'link';
			
			$form = '
			<div class="stuffbox">
				<h3><label for="title">Name</label></h3>
				<div class="inside">
					<input type="text" name="title" id="title" value="" size="30" style="width: 95%" />
					<p>Example: Nifty blogging software</p>
				</div>
			</div>

			<div class="stuffbox">
				<div class="inside">
					<table class="form-table" style="width: 100%;" cellspacing="2" cellpadding="5">
					<tr class="form-field">
						<th valign="top" scope="row"><label for="url">Web Address</label> (required)</th>
						<td>
							<input type="text" name="url" id="url" size="50" value="" style="width: 95%" />
							<p>Example: <code>http://wordpress.org/</code> &#8212; don&#8217;t forget the <code>http://</code></p>
						</td>
					</tr>
					<tr class="form-field">
						<th valign="top" scope="row"><label for="description">Description</label></th>
						<td><script type="text/javascript">edToolbar()</script><textarea name="description" id="description" cols="50" rows="10" style="width: 95%"></textarea><script type="text/javascript">var edCanvas = document.getElementById("description");</script></td>
					</tr>
					</table>
				</div>	
			</div>								
			';
			
			if ( isset($_POST['publish']) ) {		
				$description = stripslashes($_POST['description']);
				
				if ( empty($title) ) $title = $url;
					
				if ( !empty($title) && !empty($url) ) {
					$content = '<a href="'.$url.'">'.$title.'</a>';
					
					if ( !empty($description) )
						$content .= "\n\n" . $description;
				}
				
				if ( !empty($url) )
					$required = true;	
			}				
			break;
			
		case 'photo':
			$page = 'photo';
							
			$upload_path = ABSPATH . get_option('upload_path');			
			$upload = false;

			if ( is_writable($upload_path) && current_user_can('upload_files') ) {
				$enctype = ' enctype="multipart/form-data"';			
				$upload_message = ' or upload an image';			
				$upload_input = '
					<tr class="form-field">
						<th valign="top" scope="row"><label for="upload">Upload</label></th>
						<td>
							<input type="file" name="upload" id="upload" />
							<p>Uploads will be stored in <code>'.attribute_escape(str_replace(ABSPATH, '', $upload_path)).'</code> folder</p>
						</td>
					</tr>
				';
			}	
					
			$form = '
			<div class="stuffbox">
				<h3><label for="title">Photo Title</label></h3>
				<div class="inside">
					<input type="text" name="title" id="title" value="" size="30" style="width: 95%" />
				</div>
			</div>
			
			<div class="stuffbox">
				<h3><label>Photo</label> (required)</h3>
				<div class="inside">
					<table class="form-table" style="width: 100%;" cellspacing="2" cellpadding="5">
					<tr class="form-field">
						<th valign="top" scope="row"><label for="url">URL</label></th>
						<td>
							<input type="text" name="url" id="url" size="50" value="" style="width: 95%" />
							<p>Specify image by URL. This can be any valid type of image. (ie. '.get_bloginfo('url').'/photo.jpg)</p>
						</td>
					</tr>
					'.$upload_input.'
					</table>
					<p>This can be any image URL'.$upload_message.'</p>					
				</div>
			</div>

			<div class="stuffbox">
				<div class="inside">
					<table class="form-table" style="width: 100%;" cellspacing="2" cellpadding="5">
					<tr class="form-field">
						<th valign="top" scope="row"><label for="caption">Caption</label></th>
						<td>
							<input type="text" name="caption" id="caption" size="50" value="" style="width: 95%" />
							<p>Also used as alternate text for the image</p>
							<label for="disable_captions"><input id="disable_captions" name="disable_captions" type="checkbox" value="1" /> Disable caption shortcode</label>
						</td>	
					</tr>
					<tr class="form-field">
						<th valign="top" scope="row"><label for="description">Description</label></th>
						<td><script type="text/javascript">edToolbar()</script><textarea name="description" id="description" cols="50" rows="10" style="width: 95%"></textarea><script type="text/javascript">var edCanvas = document.getElementById("description");</script></td>
					</tr>
					</table>
				</div>	
			</div>							
			';

			if ( isset($_POST['publish']) ) {			
				$image_types = array(
								'image/jpeg',
								'image/gif',
								'image/png'
								);
				
				$upload_filetype = wp_check_filetype($_FILES['upload']['name']);
				$url_filetype = wp_check_filetype(basename($url));
				
				$uploads = wp_upload_dir();
				
				$caption = stripslashes($_POST['caption']);	
				$description = stripslashes($_POST['description']);
				$disable_captions = (int) $_POST['disable_captions'];
			
				if ( !empty($_FILES['upload']) || !empty($url) ) {
					// Ewwww code ahead.. help!				
					if ( is_writable($upload_path) ) {
						if ( isset($_FILES['upload']['name']) && in_array($upload_filetype['type'], $image_types) ) {
							$type = $upload_filetype['type']; 
							$file = $_FILES['upload']['name'];
							unset($url);
							$upload = true;
						} elseif ( isset($url) && in_array($url_filetype['type'], $image_types) && current_user_can('upload_files') ) {
							$type = $url_filetype['type']; 
							$file = basename($url);
							unset($_FILES['upload']['name']);
							$upload = true;	
						}
					}
				
					if ( $upload ) {							
						$number = '';			
						$filename = str_replace('#', '_', $file);
						$filename = str_replace(array( '\\', "'"), '', $filename);			
						$filename = wp_unique_filename($uploads['path'], $filename);						
						$new_file = $uploads['path'] . "/$filename";
			
						if ( isset($_FILES['upload']['name']) && in_array($upload_filetype['type'], $image_types) ) {	
							@ move_uploaded_file($_FILES['upload']['tmp_name'], $new_file);	
						}
						
						if ( isset($url) && in_array($url_filetype['type'], $image_types) ) {
							$fp = fopen($new_file, 'w');
							fwrite($fp, wp_remote_fopen($url));
							fclose($fp);	
						}
						
						$stat = stat(dirname($new_file));
						$perms = $stat['mode'] & 0000666;
						@ chmod($new_file, $perms);
						
						global $content_width; // functions.php: line 3
						
						$image_attr = getimagesize($new_file);					
						$url = $uploads['url'] . "/" . $filename;
						
						if ( $image_attr[0] > $content_width ) {
							wp_create_thumbnail($new_file, $content_width);
							$link_url = $url;	
						}								
						
						$content = ' ';					
						$required = true;
					
					} elseif ( !$upload && isset($url) && in_array($url_filetype['type'], $image_types) ) {			
						$content .= '<img src="'.$url.'" alt="'.$caption.'" title="'.$title.'" />';
						
						if ( !empty($description) )
							$content .= "\n\n" . $description;						
						
						$required = true;				
					}
				}
			}
			break;
		
		case 'chat':
			$page = 'chat';

			$form = '
			<div class="stuffbox">
				<h3><label for="title">Title</label></h3>
				<div class="inside">
					<input type="text" name="title" id="title" value="" size="30" style="width: 95%" />
				</div>
			</div>

			<div class="stuffbox">
				<div class="inside">
					<table class="form-table" style="width: 100%;" cellspacing="2" cellpadding="5">
					<tr class="form-field">
						<th valign="top" scope="row"><label for="dialogue">Dialogue</label> (required)</th>
						<td>
						<script type="text/javascript">edToolbar()</script><textarea name="dialogue" id="dialogue" cols="50" rows="20" style="width: 95%"></textarea><script type="text/javascript">var edCanvas = document.getElementById("dialogue");</script>
						<p>Example:</p>
						<p>Guy: So she got hit by a rickshaw.<br />Girl: How on earth do you get hit by a rickshaw?<br />Guy: I don\'t know, she just did.</p>		
						</td>
					</tr>
					</table>
				</div>	
			</div>				
			';
						
			if ( isset($_POST['publish']) ) {
				$dialogue = stripslashes($_POST['dialogue']);
			
				$content = $dialogue;
				
				if ( !empty($dialogue) )
					$required = true;
			}
			break;
			
		case 'text':
			wp_redirect('post-new.php');
			exit();
			break;
	endswitch; 

	if ( current_user_can('publish_posts') ) {
		global $post, $user_ID;
		
		$pending = get_others_pending($user_ID);
		$count = count($pending);
		$limit = 3;
	
		if ( $pending ) {
			echo '<div class="wrap"><p><strong>Pending Review:</strong> ';
			$i = 0;
			foreach ( $pending as $post ) {
				$i++;
				if ( $i > $limit )
					break;
				echo '<a href="post.php?action=edit&amp;post=' . $post->ID . '">';
				( '' == the_title('', '', FALSE) ) ? printf( __('Post #%s'), $post->ID ) : the_title();
				echo '</a>';
				if ( $i < min($count, $limit) )
					echo ', ';
			}
			
			if ( $i > $limit )
				printf(__(' and <a href="%s">%d more</a>'), 'edit.php?post_status=pending', $count - $limit);
			
			echo '.</p></div>';
		}
	}

	global $wpdb, $options;
	
	if ( isset($_POST['publish']) && $required ) {
		$parent_file = 'post-new.php';
		$submenu_file = 'post-new.php';
		check_admin_referer('add-post');
		
		if ( !isset($_POST['post_status']) )
			$_POST['post_status'] = current_user_can('publish_posts') ? 'publish' : 'pending';
		
		if ( !isset($_POST['comment_status']) )
			$_POST['comment_status'] = 'closed';
			
		if ( !isset($_POST['ping_status']) )
			$_POST['ping_status'] = 'closed';		
		
		$data = array(
			'post_title' => $wpdb->escape($title),
			'post_content' => $wpdb->escape($content),
			'post_date' => $date,
			'post_category' => $_POST['post_category'],
			'post_status' => $_POST['post_status'],
			'comment_status' => $_POST['comment_status'],
			'ping_status' => $_POST['ping_status'],
			'tags_input' => $_POST['tags_input']
		);
		
		$data = stripslashes_deep($data);
		$post_ID = wp_insert_post($data);
		
		if ( $upload ) {
			$attachment = array(
				'post_title' => $wpdb->escape($title),
				'post_content' => $wpdb->escape($description),
				'post_excerpt' => $wpdb->escape($caption),		
				'post_type' => 'attachment',
				'post_parent' => $post_ID,
				'post_mime_type' => $type,				
				'guid' => $url
			);
			 
			$id = wp_insert_attachment($attachment, $new_file, $post_ID);
			wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $new_file));
			
			if ( $disable_captions == '1' )
				add_filter('disable_captions', create_function('$a','return true;'));
			
			$img = get_image_send_to_editor($id, $alt=$caption, $title, $align='none', $url=$link_url, $rel=false, $size='medium');		
			$content = empty($description) ? $img : $img . "\n\n" . $description;
				
			$update = array(
				'ID' => $post_ID,
				'post_content' => $content
			);
			
			wp_update_post($update);
		}
		
		echo '<div id="message" class="updated fade"><p><strong>'.ucwords($page).' saved.</strong> <a href="'.get_permalink($post_ID).'">View post &raquo;</a></p></div>';
	}
?>

<form action="" method="post" name="post"<?php echo $enctype ?>>
<input type="hidden" name="post_category[]" value="<?php echo $options[$page] ?>" />	
<?php wp_nonce_field('add-post') ?>
			
<div class="wrap">

	<h2>Add New <?php echo ucwords($page) ?></h2>
	<br />
	<div id="poststuff">
	
		<div class="submitbox">
		
			<div id="previewview">
			</div>

			<div class="inside">
				<p><label for="comment_status"><input name="comment_status" id="comment_status" type="checkbox" value="open" <?php checked(get_option('default_comment_status'), 'open') ?> /> Allow Comments</label></p>
				<p><label for="ping_status"><input name="ping_status" id="ping_status" type="checkbox" value="open" <?php checked(get_option('default_ping_status'), 'open') ?> /> Allow Pings</label></p>

				<?php if (current_user_can('publish_posts')) : ?>
					<p><label for="post_status_private"><input id="post_status_private" name="post_status" type="checkbox" value="private" /> Keep this post private</label></p>
				<?php endif; ?>
			</div>

			<p class="submit">
				<input type="submit" class="button button-highlighted" name="publish" value="<?php if (current_user_can('publish_posts')) echo 'Publish'; else echo 'Submit for Review'; ?>" tabindex="4" />
			</p>
		
		</div> <!-- END .submitbox -->
	
		<div id="post-body">
			
			<?php echo $form ?>		
					
			<div class="stuffbox">
				<div class="inside">
					<table class="form-table" style="width: 100%;" cellspacing="2" cellpadding="5">
					<tr class="form-field">
						<th valign="top" scope="row"><label for="tags_input">Tags</label></th>
						<td>
							<input type="text" name="tags_input" id="tags_input" size="50" value="" style="width: 95%" />
							<p>Separate tags with commas</p>
						</td>
					</tr>			
					</table>					
				</div>
			</div>
		
		</div> <!-- END .post-body -->
	
	</div> <!-- END .poststuff -->

</div> <!-- END .wrap -->

</form>